<?php

namespace app\services\face;

use app\Request;
use think\facade\App;
use think\facade\Config;
use think\facade\Db;
use function session;

class FaceService
{
    public $score = 0 ;
    public $ret  ;
    protected $errorMsg = '' ;

    public static function replace_domain($url)
    {
        $url =  str_replace(request()->domain() . '/' , '' , $url) ;
        return $url ;
    }
    public function faceverify($userImg , $otherImg)
    {
        require_once App::getRootPath().'extend/face/AipFace.php' ;

        $root = self::replace_domain($userImg) ;
        $root2 = self::replace_domain($otherImg) ;

        $base = $this->base64EncodeImage($root) ;
        $base2 = $this->base64EncodeImage($root2) ;

        $APP_ID = '64656522';
        $API_KEY = 'PEWTs4XMgiSicrKR4XvJ133w';
        $SECRET_KEY = 'Llk3AXjonEDIW67iS6muIYa6jvFmf13L';

        $client = new \AipFace($APP_ID, $API_KEY, $SECRET_KEY);
        $ret = $client->match(array(
            array(
                'image' => $base,
                'image_type' => 'BASE64',
            ),
            array(
                'image' => $base2,
                'image_type' => 'BASE64',
                'face_type' => 'LIVE' ,
                'liveness_control' => 'NORMAL' ,
            ),
        ));
        Db::name('test')->insert([
            'content' => json_encode($ret ) ,
            'time' => date('Y-m-d H:i:s') ,
            'user_id' => 1 ,
        ]) ;
        if($ret['error_code'] == 0)
        {

            if($ret['result']['score'] > 70)
            {
                return true ;
            }else{
                return false ;
            }
        }
        return false ;

    }
    function base64EncodeImage($image_file)
    {
        $base64_image = '';
        $image_info = getimagesize($image_file);
        $image_data = fread(fopen($image_file, 'r'), filesize($image_file));
        //$base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data));
        $base64_image = chunk_split(base64_encode($image_data));
        return $base64_image;
    }


    public function getError(){
        return $this->errorMsg  ;
    }
    public function getRet(){
        return $this->ret  ;
    }

}